<template>
    <!-- 最外层页面于窗口同宽，使聊天面板居中 -->
    <Menu></Menu>
    <div class="home-view">
        <!-- 整个聊天面板 -->
        <div class="chat-panel">
            <!-- 左侧的会话列表 -->
            <div class="session-panel">
                <div class="title">燕知道学习助手</div>
                <div class="description">燕学园AI机器人，帮助你提高学习效率！</div>
            </div>
            <!-- 右侧的消息记录 -->
            <div class="message-panel">
                <div id="chat-message" v-loading="loading" element-loading-text="燕知道正在拼命思考！">
                    <div v-for="(item) in messageList" >
                        <div class="message avatar-message-class" v-if="item.role=='assistant'">
                            <div style="padding-right: 10px;">
                                <el-avatar
                                        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                                /></div>
                            <div class="message received">{{item.content}}</div>
                        </div>
                        <div class="message sent" v-if="item.role=='user'">{{item.content}}</div>
                    </div>
                </div>



                <div class="send-message">
                    <el-row :gutter="0">
                        <el-col :span="20"><div class="grid-content ep-bg-purple" />

                            <el-input v-model="inputMessage"
                                      type="textarea"
                                      placeholder="有不知道就问燕知道"
                            ></el-input>
                        </el-col>
                        <el-col :span="4">

                            <el-button
                                    type="primary"
                                    style="height: 100%"
                                    :disabled="buttonDisabled"
                                    @click="sendMessage"
                            >发送</el-button>

                        </el-col>
                    </el-row>
                </div>
                <!--                    水水水水水水水水水水水水-->

            </div>
        </div>
    </div>
</template>

<script setup>
    import {ref} from 'vue'
    import axios from "axios";
    import {ElMessage} from "element-plus";

    const inputMessage = ref("");
    const buttonDisabled = ref(false);
    const AK = "dRrsjDxa4j3xDOuTmwvfDjWM"
    const SK = "OZOQ2tkuDcQMFnkSLB5v3r1NWHmzPM14"
    const messageList = ref([]);
    const loading = ref(false);

    async function sendMessage() {
        // buttonRef.disabled = true;
        if (inputMessage.value!=""){
            buttonDisabled.value = true
            messageList.value.push({"role":'user',"content":inputMessage.value})
            inputMessage.value = "";
            setTimeout(()=>{
                loading.value = true;
            },700)


            try {
                const aiResponse = await getApiResponse();
                console.log(aiResponse)
                messageList.value.push({"role":'assistant',"content":aiResponse.data.result});
                // console.log(messageList.value)
                loading.value = false;

            }catch (e) {
                ElMessage.error("机器人错误，请联系管理员")
            }
            buttonDisabled.value = false;

        }
    }

    async function getApiResponse() {
        const accessToken = await getAccessToken();

        const options = {
            method: 'POST',
            url:
                '/baiduApi/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=' + accessToken,
            headers: {
                'Content-Type': 'application/json',
            },
            data: JSON.stringify({
                temperature: 0.95,
                top_p: 0.8,
                penalty_score: 1,
                disable_search: false,
                enable_citation: false,
                system: "我是燕知道，燕学园在线学习平台的AI机器人，帮助你快速学习！",
                response_format: 'text',
                messages: messageList.value
            }),
        };
        // console.log(options.data)

        try {
            const response = await axios(options);
            // console.log(response.data);
            return response
        } catch (error) {
            throw new Error(error);
        }
        // return new Promise()
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    function getAccessToken() {

        let options = {
            method: 'POST',
            url: '/baiduApi/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        }

        return new Promise((resolve, reject) => {
            axios(options)
                .then(response => {
                    // console.log(response.data)
                    resolve(response.data.access_token);
                })
                .catch(error => {
                    reject(error);
                });
        });
    }

    // axios({
    //     'method': 'POST',
    //     'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    //
    // })

</script>

<style  scoped>
    .home-view {
        display: flex;
        /* 与窗口同宽 */
        /*width: 100vw;*/
        /* 水平方向上剧中 */
        justify-content: center;

    .chat-panel {
        /* 聊天面板flex布局，让会话列表和聊天记录左右展示 */
        display: flex;
        /* 让聊天面板圆润一些 */
        border-radius: 20px;
        background-color: white;
        /* 给一些阴影 */
        box-shadow: 0 0 20px 20px rgba(black, 0.05);
        /* 与上方增加一些间距 */
        margin-top: 20px;
    /* 左侧聊天会话面板*/
    .session-panel {
        background-color: rgb(231, 248, 255);
        /*width: 300px;*/
        width: 200px;
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
        padding: 20px;
        position: relative;
        border-right: 1px solid rgba(black, 0.07);
    /* 标题*/
    .title {
        margin-top: 20px;
        font-size: 20px;
    }
    /* 描述*/
    .description {
        color: rgba(black, 0.7);
        font-size: 10px;
        margin-top: 10px;
    }
    }
    /* 右侧消息记录面板*/
    .message-panel {
        width: 700px;
        /*height: 600px;*/
        height: 85vh;
    }
    }
    }
    .send-message{
        /*display: flex;*/
        /*align-items: center;*/
        /*justify-content: space-between;*/
        /*height: 500px;*/
        padding: 10px;
        background-color: #fff;
        border-top: 1px solid #ccc;

    }
    .message {
        clear: both;
        padding: 8px;
        margin-bottom: 8px;
        border-radius: 5px;
        max-width: 70%;
        word-wrap: break-word;
    }
    .message.sent {
        float: right;
        background-color: #4caf50;
        color: #fff;
    }
    .message.received {
        float: left;
        background-color: #e0e0e0;
    }
    #chat-message{
        flex: 1; /* 让消息容器占据剩余空间 */
        height: 70vh;
        padding: 20px 10px 10px 10px;
        overflow-y: auto;
        background-color: #fff;
    }
    .avatar-message-class{
        display: flex;
    }


</style>